#include "StdAfx.h"
#include "scenario.h"

using namespace System::IO;
using namespace System::Diagnostics;
scenario::scenario(System::String^ fileName)
{
	//==========================================================================================
	//																			initialize
	//==========================================================================================
	IsReady=false;
	FileName=fileName;
	numOfScenes=0;
	numOfLines=0;
	projectPath=System::IO::Path::GetDirectoryName(fileName);
	fileProjectName=System::IO::Path::GetFileNameWithoutExtension(fileName);
	//==========================================================================================
	//																			functions
	//==========================================================================================
	ReadScenario();
	verifyFinalAndSound();
	
}
bool scenario::isReady()
{
	return IsReady;
}
bool scenario::ReadScenario(void)
{
	//System::IO::Compression::GZipStream ^ qweewq;
	bool result=false;
	System::IO::StreamReader^ reader=gcnew System::IO::StreamReader(FileName);
	String ^ vers;
	int j=0;
	if(File::Exists(this->FileName))
	{
		
		
		String^ buf;
		vers=reader->ReadLine();
		textOfScenary=gcnew array<String^>(2048);
		
		while(!reader->EndOfStream && numOfLines!=2040)
		{
			buf=reader->ReadLine();
			if(buf->StartsWith("//"))
			{
				int i=0;
			}
			else
			{
				textOfScenary[numOfLines]=gcnew String("");
				textOfScenary[numOfLines]=buf;
				numOfLines++;
			}
		}
		reader->Close();
		
		
		if(vers!="v.0.0.1")
		{
			return result;
		}	
		scenes=gcnew array<Scene^>(50);
		int i = 0;
		
		String ^buffer2;
		// ===========================================================================================
		// ===========================================================================================
		//																			here reading of text and analisys of it
		// ===========================================================================================
		// ===========================================================================================
		while(i!=numOfLines && numOfScenes!=50)
		
		{
			if(textOfScenary[i]->StartsWith("Scene"))
			{
				
				scenes[numOfScenes]=gcnew Scene(Path::GetDirectoryName(FileName));
				scenes[numOfScenes]->SetInnerName(textOfScenary[i]->Substring(6));
				numOfScenes++;
			}
			else
			{
				analyse(textOfScenary[i]);
			}
			
			i++;
			
		}
		
		
		// ===========================================================================================
		// ===========================================================================================
		IsReady=true;
		
		
	}
	
	return result;
}
		
bool scenario::WriteScenario(void)
{
	bool result=false;
	try
	{
		if(File::Exists(Path::Combine(projectPath, fileProjectName + ".bks")))
		{File::Delete(Path::Combine(projectPath, fileProjectName + ".bks"));}
		if(File::Exists(Path::Combine(projectPath, fileProjectName + ".scn")))
		{File::Move(Path::Combine(projectPath, fileProjectName + ".scn"),Path::Combine(projectPath, fileProjectName + ".bks"));}
		StreamWriter^ writer_=gcnew StreamWriter(Path::Combine(projectPath, fileProjectName + ".scn"));
		writer_->WriteLine("v.0.0.1");
		int i=0;int k=0;
		while(i<numOfScenes)
		{
			while(k<numOfScenes)
			{
				if(scenes[k]->isReady())
				{
					if(scenes[k]->GetMajorNumber()!=i){}else{
					writer_->WriteLine("Scene " + scenes[k]->GetInnerName());
					writer_->WriteLine(scenes[k]->GetInnerName() + ".name=" + scenes[k]->GetOuterName());
					writer_->WriteLine(scenes[k]->GetInnerName() + ".number=" + scenes[k]->GetMajorNumber());
					writer_->WriteLine(scenes[k]->GetInnerName() + ".description=" + scenes[k]->GetDescription());
					writer_->WriteLine(scenes[k]->GetInnerName() + ".duration=" + scenes[k]->GetDuration());}
				}
				k++;
			}
			
			i++;k=0;

		}
		writer_->Close();
		result=true;
	}
	catch(String^ ex){}
	return result;
}
bool scenario::Save(void)
{
	return WriteScenario();
}

		// ===========================================================================================
		// ===========================================================================================
		//																			here reading of text and analisys of it
		// ===========================================================================================
		// ===========================================================================================
void scenario::analyse(String^ str)
{
		bool r;
		String^ left;
		String^ right;
		String^ W="";
		int i = 0;
		String^ nameOfFeature;
		String^ propertyOfFeature;

		if(str->Length==0){return;}
		while((W!=" " && W!="=") && i<str->Length)
		{
			W=str->Substring(i,1);
			i++;
		}
		left=str->Substring(0,i-1);
		while(W!=" " && W!="=")
		{
			W=str->Substring(i,1);
			i++;
		}
		right=str->Substring(i);
		while(W!=" " &&W!="\n" && i<str->Length)
		{
			W=str->Substring(i,1);
			i++;
		}
		i=0;
		W="+";
		while(W!=".")
		{
			W=str->Substring(i,1);
			i++;
		}
		nameOfFeature=left->Substring(0,i-1);

		int ik=0;
		int boofer=0;
		while(ik<numOfScenes)
		{
			if(nameOfFeature==scenes[ik]->GetInnerName())
			{boofer=ik;ik=numOfScenes;}
			ik++;
		}
		
		propertyOfFeature=left->Substring(i);

		if(propertyOfFeature->Contains("name"))
		{
			scenes[boofer]->SetOuterName(right);
		}
		else if(propertyOfFeature->Contains("number"))
		{
			scenes[boofer]->SetMajorNumber(System::Convert::ToInt32(right));
			//if(!scenes[boofer]->GetMajorNumber() < scenes[boofer-1]->GetMajorNumber()){}
			//else
			//{
				//scenes[boofer+1]=scenes[boofer];
				//scenes[boofer]=scenes[boofer-1];
				//scenes[boofer-1]=scenes[boofer+1];
			//}
		}
		else if(propertyOfFeature->Contains("description"))
		{
			scenes[boofer]->SetDescription(right);
		}
		else if(propertyOfFeature->Contains("duration"))
		{
			scenes[boofer]->SetDuration(System::Convert::ToInt32(right));
		}
		return;
}
		// ===========================================================================================
		// ===========================================================================================
		//																			here the end of reading and analisys
		// ===========================================================================================
		// ===========================================================================================
Scene^ scenario::GetNextScene(int i)
{
	if(i<numOfScenes && i>-1)
	{
		return scenes[i];
	}
	else
	{throw numOfScenes;}
}
int scenario::GetQuantityOfScenes(void)
{
	return numOfScenes;
}
bool
scenario::verifyFinalAndSound()
{
	if(Directory::Exists(Path::Combine(projectPath, "final")))
	{}
	else
	{Directory::CreateDirectory(Path::Combine(projectPath, "final"));}
	if(Directory::Exists(Path::Combine(projectPath, "Sound")))
	{}
	else
	{Directory::CreateDirectory(Path::Combine(projectPath, "Sound"));}
	return true;
}


bool scenario::addScene(int number)
{
	bool result=false;
	//===================================================================================================
	//===================================================================================================
	int i=0;//listBox1->SelectedIndex;
	//scenes[numOfScenes]=gcnew Scene(projectPath);
	if(number!=-1)
	{
		scenes[numOfScenes]=gcnew Scene(projectPath);
		while(i<numOfScenes)
		{
			//sc=scenes->GetNextScene(i);
			//richTextBox1->Text=sc->GetDescription();
			if(scenes[i]->GetMajorNumber()<number){}
			else{scenes[i]->SetMajorNumber(scenes[i]->GetMajorNumber()+1);}
			i++;
		}
		scenes[numOfScenes]->SetDescription("null");
		scenes[numOfScenes]->SetDuration(5);
		scenes[numOfScenes]->SetInnerName("var");
		scenes[numOfScenes]->SetOuterName("aliaScaena");
		scenes[numOfScenes]->SetMajorNumber(number);
		numOfScenes++;
	}
	//===================================================================================================
	//===================================================================================================

	return result;
}




bool scenario::addScene(int number, String^ outerName_)
{
	bool result=false;
	//===================================================================================================
	//===================================================================================================
	int i=0;//listBox1->SelectedIndex;
	//scenes[numOfScenes]=gcnew Scene(projectPath);
	if(number!=-1)
	{
		scenes[numOfScenes]=gcnew Scene(projectPath);
		while(i<numOfScenes)
		{
			//sc=scenes->GetNextScene(i);
			//richTextBox1->Text=sc->GetDescription();
			if(scenes[i]->GetMajorNumber()<number){}
			else{scenes[i]->SetMajorNumber(scenes[i]->GetMajorNumber()+1);}
			i++;
		}
		scenes[numOfScenes]->SetDescription("null");
		scenes[numOfScenes]->SetDuration(5);
		scenes[numOfScenes]->SetInnerName("var" + number.ToString());
		scenes[numOfScenes]->SetOuterName(outerName_);
		scenes[numOfScenes]->SetMajorNumber(number);
		numOfScenes++;
	}
	//===================================================================================================
	//===================================================================================================

	return result;
}
bool scenario::makeOutput(String^ pathToFFmpEg)
{
	bool result=false;
	String^ _path_=pathToFFmpEg;
	if(_path_=="null"){return result;}
	else
	{
		if(!File::Exists(Path::Combine(_path_,"ffmpeg.exe"))){return result;}
		else
		{
			int iter=0;
			String^ fileAVI;
			String^ outDir=Path::Combine(projectPath, "final");
			String^ newName;
			while(iter<numOfScenes)
			{
				fileAVI=Path::Combine(projectPath, scenes[iter]->GetOuterName());
				fileAVI=Path::Combine(fileAVI, "render_1.avi");
				if(File::Exists(fileAVI))
				{
					if(iter<10)
					{
						newName=Path::Combine(outDir, "000" + iter.ToString() + "_" + scenes[iter]->GetOuterName() + ".avi");
					}
					else if(iter>9 && iter<100)
					{
						newName=Path::Combine(outDir, "00" + iter.ToString() + "_" + scenes[iter]->GetOuterName() + ".avi");
					}
					//newName=Path::Combine(newName,".avi");
					if(!File::Exists(newName))	File::Copy(fileAVI,newName);
					makeIt(Path::Combine(_path_,"ffmpeg.exe"),newName);
					//ffmpeg -i "%~dp0render\%name%_%file%.avi" -sameq "%~dp0\render\%name%_%file%.mpg"
				}
				iter++;
			}
		}
	}
	return result;
}
void scenario::makeIt(String^ ffmpeg_, String^ avi_)
{
	String^ strokaOut, ^err;
	Process^ myHandle = gcnew Process();
	ProcessStartInfo^ myProcInfo=gcnew ProcessStartInfo(ffmpeg_);
	//ProcessStartInfo^ myProcInfo=gcnew ProcessStartInfo("qwe.bat");
	//myProcInfo->WorkingDirectory= Path::GetDirectoryName(avi_);//ffmpeg_);
	myProcInfo->UseShellExecute=true;
	//myProcInfo->RedirectStandardOutput=true;
	myProcInfo->CreateNoWindow=true;
	myProcInfo->WindowStyle::set(ProcessWindowStyle::Normal);
	myProcInfo->Arguments=" -i \"" + avi_ + "\" -sameq \"" + avi_ + ".mpg\"";//avi_ + " >> qwerty.txt";
	myHandle->StartInfo=myProcInfo;
	myHandle->Start();
	myHandle->WaitForExit();
	//try
	//{
		
		//strokaOut=myHandle->StandardOutput->ReadToEnd()->ToString();
		//err=myHandle->StandardError->ReadToEnd()->ToString();
		//System::Windows::Forms::MessageBox::Show(strokaOut);
	//}
	//catch(String^ err){}
	myHandle->Close();
}
bool scenario::addSoundToVideo(String^ ffmpeg_)
{
	bool result=false;
	String^ strokaOut;
	Process^ myHandle = gcnew Process();
	ProcessStartInfo^ myProcInfo=gcnew ProcessStartInfo(ffmpeg_);
	myProcInfo->UseShellExecute=false;
	myProcInfo->RedirectStandardOutput=true;
	myProcInfo->CreateNoWindow=true;
	myProcInfo->WindowStyle::set(ProcessWindowStyle::Hidden);
	//myProcInfo->Arguments=" -i " + avi_ + " -sameq " + avi_ + ".mpg";
	//==========================================================================================
	//==========================================================================================
	//																											be careful here!!!!!!!!
	//==========================================================================================
	//==========================================================================================
	myHandle->StartInfo=myProcInfo;
	myHandle->Start();
	myHandle->WaitForExit();
	try
	{
		strokaOut=myHandle->StandardOutput->ReadToEnd()->ToString();
		System::Windows::Forms::MessageBox::Show(strokaOut);
	}
	catch(String^ err){}
	myHandle->Close();
	return result;
}

String^ scenario::GetProjectPath(void)
{
	return projectPath;
}